package handle

import (
	"AcsGo/config"
	"AcsGo/internal/domain"
	"AcsGo/internal/model"
	"AcsGo/internal/util"
	"database/sql"
	"strconv"
)

// 借书

func HandlebookBorrow(str string) (string, error) {
	success := ""
	rdbm := ""
	rdname := ""
	bkbm := ""
	bkTitle := ""
	dueDate := ""
	price := ""
	currentDate, dueDate1, currentTime, _ := util.GetFormattedDatesAndTime()
	lg.Debugf("currentDate: %v, dueDate: %v, currentTime: %v", currentDate, dueDate1, currentTime)
	var queryResponse *domain.BookBorrowBookResponse
	queryRequest, err := domain.HandleBorrowBookRequest(str)
	if err != nil {
		queryResponse = domain.InitBorrowBookResponse(success, rdbm, rdname, bkbm, bkTitle, dueDate, price)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("HandleBorrowBookRequest: %v", sb)
		return sb, err
	}
	lg.Debugf("HandleBorrowBookRequest: %v", queryRequest)
	db, err := model.ConnectDB()
	if err != nil {
		return "", err
	}
	publicRecord, err := model.GetPbBookRecordBy(db, queryRequest.ItemIdentifier.Value)
	if err != nil {
		queryResponse = domain.InitBorrowBookResponse(success, rdbm, rdname, bkbm, bkTitle, dueDate, price)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("GetPbBookRecordBy: %v", sb)
		return sb, err
	}
	bookid, _ := strconv.Atoi(publicRecord.BKRECD)

	book, err := model.GetBook(db, bookid)
	if err != nil {
		queryResponse = domain.InitBorrowBookResponse(success, rdbm, rdname, bkbm, bkTitle, dueDate, price)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("GetBook: %v", sb)
		return sb, err
	}
	reader, err := model.GetReaderByBm(db, queryRequest.PatronIdentifier.Value)
	if err != nil {
		queryResponse = domain.InitBorrowBookResponse(success, rdbm, rdname, bkbm, bkTitle, dueDate, price)
		sb, _ := queryResponse.StringFormat()
		lg.Debugf("GetReader: %v", sb)
		return sb, err
	}
	// 判断最大借书数量
	ID := strconv.Itoa(reader.ID)
	pbs, _ := model.GetPbBookRecord(db, ID)
	num := len(pbs)
	typeStr := config.LoadType()
	comss := util.ParseLType(typeStr)
	lg.Debugf("comss: %v num %d LType %s", comss, num, reader.LType)
	for _, coms := range comss {
		if coms.TypeID == reader.LType {
			if num >= coms.Value {
				success = "2"
				rdbm = queryRequest.PatronIdentifier.Value
				rdname = reader.Name
				bkTitle = strconv.Itoa(coms.Value)
				queryResponse = domain.InitBorrowBookResponse(success, rdbm, rdname, bkbm, bkTitle, dueDate, price)
				sb, _ := queryResponse.StringFormat()
				lg.Debugf("success: %v", sb)
				return sb, err
			}
		}
	}
	// update t_publicrecord set gox ='1' , jcrq ='20240725' , jctm ='08:54:10' , autherbm ='167' , yhrq ='20250121' where barbm ='ST000001'
	publicRecord.GOX = "1"
	publicRecord.JCRQ = sql.NullString{String: currentDate, Valid: true}
	publicRecord.JCTM = sql.NullString{String: currentTime, Valid: true}
	publicRecord.AutherBM = sql.NullString{String: strconv.Itoa(reader.ID), Valid: true}
	err = model.UpdatePublicRecord(db, publicRecord)
	if err != nil {
		return "", err
	}
	// UPDATE t_reader SET xyjs = 1 WHERE bm = '0600039733'
	reader.Xyjs = 1
	err = model.UpdateReader(db, reader)
	if err != nil {
		return "", err
	}

	// insert into t_processlog ( process , rdbm , rdmc , bkbm , indexnb , titile , admintm , admin , yhrq , mny , adminsj , rdid , bkid , ltype , unit , adress )
	//  values ( '借出' , '0600039733' , 'CS' , 'ST000001' , 'K825.42/1' , '一问一世界' , '20240725' , 'tsg' , '20250121' , ''
	// , '08:54:10' , '167' , '47644' , '02' , '' , '01' )

	var processLog = model.ProcessLog{
		Process: "借出",
		RDBM:    reader.BM,
		RDMC:    reader.Name,
		BKBM:    publicRecord.BARBM,
		IndexNB: book.IndxNb,
		Titile:  book.Name,
		Admintm: currentDate,
		Admin:   "tsg",
		YHRQ:    dueDate1,
		MNY:     book.Price,
		AdminSJ: currentTime,
		RDID:    sql.NullString{String: strconv.Itoa(reader.ID), Valid: true},
		BKID:    sql.NullString{String: strconv.FormatInt(book.ID, 10), Valid: true},
		LType:   sql.NullString{String: reader.LType, Valid: true},
		Unit:    sql.NullString{String: reader.Unit.String, Valid: true},
		Adress:  sql.NullString{String: reader.Address.String, Valid: true},
	}
	err = model.InsertProcessLog(&processLog, db)
	if err != nil {
		return "", err
	}
	success = "1"
	rdbm = reader.BM
	rdname = reader.Name
	bkbm = publicRecord.BARBM
	bkTitle = book.Name
	dueDate = dueDate1
	price = publicRecord.Price

	queryResponse = domain.InitBorrowBookResponse(success, rdbm, rdname, bkbm, bkTitle, dueDate, price)
	sb, _ := queryResponse.StringFormat()
	lg.Debugf("success: %v", sb)
	return sb, err
}
